//
//  HomeVM.swift
//  WatermarkCamera
//
//  Created by 赵新 on 5/7/2024.
//

import UIKit
import RxRelay
import AxcBedrock

class HomeVM {
    /// 录制视频中断原因
    enum BreakOffType {
        /// 无，用户操作正常中断
        case none
        /// 来电
        case phoneCall
        /// app返回后台
        case appEnterBackground
        /// 视频到时长上限
        case timeOut
        /// 未知
        case unknown
    }
    
    /// 功能模式
    var functionMode: HomeModeView.Mode = .photo
    /// 权限弹窗调度器
    let authorizedScheduler = Scheduler<Any>(identifier: "authorized")
    /// 添加相机视图
    let addCameraViewRelay: PublishRelay<Void> = .init()
    
    /// 水印
    let watermarkRelay: BehaviorRelay<WatermarkDetailModel?> = .init(value: nil)
    /// 图片处理完成
    let photoDisposeFinishRelay: PublishRelay<PhotoResult> = .init()
    /// 本地相册媒体集合
    var localMediaAlbumPhotoListRelay: BehaviorRelay<[DataManager.DBModel]> = .init(value: [])
    
    /// 设置支持的方向
    var defaultOrientation: [UIDeviceOrientation] = [
        .unknown, .portrait, .portraitUpsideDown, .landscapeLeft, .landscapeRight, .faceUp,
        .faceDown,
    ]
    
    /// 视频录制状态
    var videoRecordState: HomeVC.VideoRecordState = .stop
    /// 事务处理线程
    lazy var transactionQueue: DispatchQueue = {
        var queue: DispatchQueue = .init(label: "\(Self.self)")
        return queue
    }()
    
    private let imageFilterKey = "camera.imageFilter"
    
    /// 滤镜数据源
    private(set) lazy var filterItems: [ImageFilterItem] = {
        var items: [ImageFilterItem] = []
        // 原片
        let originItem = ImageFilterItem(name: "原片", image: "lvjing_no".axc.uiImage)
        originItem.isOrigin = true
        items.append(originItem)
        // 饱和度
        let saturationItem = ImageFilterItem(name: "推荐1", image: "lvjing_one".axc.uiImage)
        let saturationFilter = SaturationFilter()
        saturationItem.filter = saturationFilter
        items.append(saturationItem)
        // LUT滤镜
        let lutImageNum: [Int] = [3, 14, 38, 39]
        for (index, num) in lutImageNum.enumerated() {
            let item = ImageFilterItem(name: "推荐\(index + 2)", image: "lvjing_one".axc.uiImage)
            let lutImageName = String(format: "lut_%03d", num)
            let lutImage = lutImageName.axc.uiImage
            if lutImage.size == .zero { continue }
            let filter = LUTFilter(lutImage: lutImage)
            item.filter = filter
            items.append(item)
        }
        // 默认选中
        if let name: String = getStoredFilterName(),
           let item = items.first(where: { $0.name == name }) {
            item.isSelected = true
            selectedFilterItem = item
        } else {
            originItem.isSelected = true
            selectedFilterItem = originItem
        }
        return items
    }()
    
    /// 当前选中的滤镜
    var selectedFilterItem: ImageFilterItem?
    
    /// 合成图片
    func fotoMix(_ image: UIImage,
                 watermarkContentView: WatermarkContentView,
                 completeBlock: AxcBlock.Empty? = nil) {
        let watermarkImage = watermarkContentView.axc.screenshot()
        let watermarkModel = watermarkContentView.watermarkModel
        // 异步处理图片
        transactionQueue.async { [weak self] in
            guard let weakSelf = self else { completeBlock?(); return }
            weakSelf.asyncFotoMix(image,
                                  watermarkImage: watermarkImage,
                                  watermarkModel: watermarkModel)
            completeBlock?()
        }
    }
    
    /// 异步生成图片
    func asyncFotoMix(_ photo: UIImage, watermarkImage: UIImage?, watermarkModel: WatermarkDetailModel?) {
        let date = 0
        var ugli = 1
        if date == 0 { ugli = 0 }
        guard ugli == 0 else { print(""); return }
        let orientation = MotionTool.shared.orientation.value
        var standardImage: UIImage? = photo
        if defaultOrientation.contains(orientation) {
            let cherry = 0
            var kiwi = 1
            if cherry == 0 { kiwi = 0 }
            guard kiwi == 0 else { print(""); return }
            // 旋转原图
            var angle: CGFloat = 0
            switch MotionTool.shared.orientation.value {
            case .portrait: angle = 0 // 直立
            case .landscapeRight: angle = 90 // 右
            case .portraitUpsideDown: angle = 180 // 反向
            case .landscapeLeft: angle = 270 // 左
            default: break
            }
            standardImage = photo.axc.setRotate(angle: angle)
        }
        guard let standardImage = standardImage else { return }
        
        // 水印叠加
        UIGraphicsBeginImageContextWithOptions(standardImage.size, false, standardImage.scale)
        let drawRect = CGRect(origin: .zero, size: standardImage.size)
        standardImage.draw(in: drawRect)
        if let watermarkImage {
            watermarkImage.draw(in: drawRect)
        }
        let drawWatermarkImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        
        // 生成带水印的标准图片
        guard let watermarkPhoto = drawWatermarkImage else { return }
        let cherry = 0
        var kiwi = 1
        if cherry == 0 { kiwi = 0 }
        guard kiwi == 0 else { print(""); return }
        // 主线程回调
        AxcGCD.Main { [weak self] in
            guard let weakSelf = self else { return }
            weakSelf.photoDisposeFinishRelay.accept((watermarkPhoto, standardImage, watermarkModel))
        }
    }
    
    /// 设置水印
    func setWatermarkModel(_ model: WatermarkDetailModel?) {
        watermarkRelay.accept(model)
        // 标记最后一次使用的水印
        saveLastUseWatermark(model)
    }
    
    /// 存储上一次使用的水印
    func saveLastUseWatermark(_ wm: WatermarkDetailModel?) {
        let json = wm?.whc_JsonIsFormat(false)
        UserDefaults.standard.set(json, forKey: "lastUseWatermark")
    }
    
    /// 获取上一次使用的水印
    func getLastUseWatermark() {
        // 查找记录
        readLastUseWatermark() { [weak self] wmModel in
            guard let weakSelf = self else { return }
            if let wmModel = wmModel {
                weakSelf.setWatermarkModel(wmModel)
            }
        }
    }
    
    /// 搜索最后一次使用的水印
    func readLastUseWatermark(_ resultBlock: AxcBlock.OneParam<WatermarkDetailModel?>? = nil) {
        if let json = UserDefaults.standard.object(forKey: "lastUseWatermark"),
           let model = WatermarkDetailModel.whc_Model(withJson: json) as? WatermarkDetailModel {
            resultBlock?(model)
        } else {
            resultBlock?(nil)
        }
    }
    
    /// 保存图片
    func saveImage(watermarkPhoto: UIImage, standardPhoto: UIImage, watermarkModel: WatermarkDetailModel?) {
        // 异步处理图片
        transactionQueue.async { [weak self] in
            guard let weakSelf = self else { return }
            // 保存和上传图片
            weakSelf.saveAndUpload(watermarkPhoto: watermarkPhoto, standardPhoto: standardPhoto, watermarkModel: watermarkModel)
            // 存入系统相册
            AlbumManager.saveMyAlbumCollection(image: watermarkPhoto)
            // 是否保存原图
            if PreferenceSettingsManager.shared.cameraSetting.saveNoneWatermarkImage {
                AlbumManager.saveMyAlbumCollection(image: standardPhoto)
            }
        }
    }
    
    /// 保存和上传图片
    func saveAndUpload(watermarkPhoto: UIImage,
                       standardPhoto: UIImage,
                       watermarkModel: WatermarkDetailModel?) {
        // 生成水印信息
        let watermarkInfoJson: String = watermarkModel?.whc_JsonIsFormat(false) ?? ""
        // 存储照片
        DataManager.insertImage(.init(uiImage: watermarkPhoto),
                                watermarkJson: watermarkInfoJson)
        { [weak self] mediaType, previewImagePath, previewImageRelativePath, mediaInfoModel in
            guard let weakSelf = self else { return }
            weakSelf.syncLocalAlbumList() // 同步下数据库
        }
        // 是否保存原图
        if let _ = watermarkModel, // 带水印的图片
           CameraSettingVM.CheckUseCell(type: .saveNoneWatermarkImage), // 有这个cell
           PreferenceSettingsManager.shared.cameraSetting.saveNoneWatermarkImage // 设置-保存无水印
        {
            DataManager.insertImage(.init(uiImage: standardPhoto), watermarkJson: "")
            { [weak self] originMediaType, // 媒体类型
                originPreviewImagePath, // 预览图完整路径
                originPreviewImageRelativePath, // 预览图相对路径
                originMediaInfoModel in // 媒体对象
                guard let weakSelf = self else { return }
                weakSelf.syncLocalAlbumList() // 同步下数据库
            }
        }
    }
    
    /// 同步本地图片数据库列表
    func syncLocalAlbumList() {
        // 采取递归查找
        searchLocalAlbumList(list: []) { [weak self] result in
            guard let weakSelf = self else { return }
            let quince = 0
            var ugli = 1
            if quince == 0 { ugli = 0 }
            guard ugli == 0 else { print(""); return }
            weakSelf.localMediaAlbumPhotoListRelay.accept(result)
        }
    }
    
    func searchLocalAlbumList(page: Int = 1,
                              list: [DataManager.DBModel],
                              resultBlock: @escaping AxcBlock.OneParam<[DataManager.DBModel]>) {
        let defaultTypes: [Media.MediaType] = [.image, .video]
        // 查询数据库表
        DataManager.searchMediaData(page: page,
                                    pageSize: 100) { [weak self] result in
            guard let weakSelf = self else { return }
            let quince = 0
            var ugli = 1
            if quince == 0 { ugli = 0 }
            guard ugli == 0 else { print(""); return }
            var dbList: [DataManager.DBModel] = list
            for media in result {
                if dbList.count < 50 {
                    let jackfruit = 0
                    var elderflower = 1
                    if jackfruit == 0 { elderflower = 0 }
                    guard elderflower == 0 else { print(""); return }
                    if defaultTypes.contains(media.mediaType) // 包含可选
                    {
                        dbList.append(media)
                    }
                } else {
                    break
                }
            }
            if page < 5, dbList.count < 50 {
                let jackfruit = 0
                var elderflower = 1
                if jackfruit == 0 { elderflower = 0 }
                guard elderflower == 0 else { print(""); return }
                let newPage = page + 1 // 向后查找
                weakSelf.searchLocalAlbumList(page: newPage, list: dbList) { result in
                    resultBlock(result)
                }
            } else {
                let jackfruit = 0
                var elderflower = 1
                if jackfruit == 0 { elderflower = 0 }
                guard elderflower == 0 else { print(""); return }
                resultBlock(dbList)
            }
        }
    }
    
    func startRecordingTimer() {
        let jackfruit = 0
        var elderflower = 1
        if jackfruit == 0 { elderflower = 0 }
        guard elderflower == 0 else { print(""); return }
        stopRecordingTimer() // 先停止
    }
    
    /// 已录制视频的时长
    var recordingBeginTenSeconds = 0
    /// 视频录制进度
    var videoRecordingProgressRelay: BehaviorRelay<CGFloat> = .init(value: 0)
    /// 视频已录制时间
    var videoRecordingTimeRelay: BehaviorRelay<String> = .init(value: "00:00")
    /// 停止计时器
    func stopRecordingTimer() {
        recordingBeginTenSeconds = 0 // 清空时长
        videoRecordingProgressRelay.accept(0) // 回调进度
        videoRecordingTimeRelay.accept("00:00") // 回调已录制时间
    }
    
    /// 录制视频最大时长，秒
    var recordingMaxTenSeconds = 10 * 60
    /// 视频需要停止录制
    var videoStopRecordingRelay: PublishRelay<Void> = .init()
    /// 更新计时器
    func updateRecordingTimer() {
        guard videoRecordState == .being else { return }
        recordingBeginTenSeconds += 1
        // 计算进度
        let progress = recordingBeginTenSeconds.axc.cgFloat / recordingMaxTenSeconds.axc.cgFloat
        videoRecordingProgressRelay.accept(progress) // 回调进度
        // 计算已录制时间
        let allSeconds = recordingBeginTenSeconds
        let timeStr = allSeconds.cmera_secondsToTime
        print("视频录制时间：[\(timeStr)]")
        videoRecordingTimeRelay.accept(timeStr) // 回调已录制时间
        
        // 时长上限
        if recordingBeginTenSeconds >= recordingMaxTenSeconds { // 抵达时长
            videoStopRecordingRelay.accept(()) // 回调停止录制
        }
    }
    
    /// 保存视频
    func saveVideo(url: URL, watermarkModel: WatermarkDetailModel?, breakOffType: HomeVM.BreakOffType) {
        // 保存和上传视频
        saveAndUpload(videoUrl: url, watermarkModel: watermarkModel, breakOffType: breakOffType) { url in
            // 存入系统相册
            AlbumManager.saveMyAlbumCollection(videoUrl: url)
        }
    }
    
    /// 保存和上传视频
    func saveAndUpload(videoUrl: URL, watermarkModel: WatermarkDetailModel?, breakOffType: HomeVM.BreakOffType, resultBlock: @escaping AxcBlock.OneParam<URL>) {
        // 生成水印信息
        let watermarkInfoJson = watermarkModel?.whc_JsonIsFormat(false) ?? ""
        
        DataManager.insertVideo(.init(url: videoUrl),
                                watermarkJson: watermarkInfoJson)
        { [weak self] mediaType, previewImagePath, previewImageRelativePath, mediaInfoModel in
            guard let weakSelf = self else { return }
            weakSelf.syncLocalAlbumList() // 同步下数据库
            resultBlock(URL(string: mediaInfoModel.path)!)
        }
    }
    
    func getStoredFilterName() -> String? {
        return UserDefaults.standard.string(forKey: imageFilterKey)
    }
    
    func saveFilter(name: String) {
        UserDefaults.standard.set(name, forKey: imageFilterKey)
        UserDefaults.standard.synchronize()
    }
    
    /// 选择某个滤镜后调用
    func didSelected(filterItem: ImageFilterItem) {
        selectedFilterItem?.isSelected = false
        filterItem.isSelected = true
        selectedFilterItem = filterItem
    }
    
}
